<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;" v-loading="loading_search">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-select v-model="filters.provinceCode" placeholder="请选择省份" @change="getCityListByProvince(filters.provinceCode)" style="width:150px;" clearable>
						<el-option v-for="(item,i) in provinceList" :key="i" :label="item.name" :value="item.code"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select v-model="filters.cityCode" placeholder="请选择地市" @change="getDistrictListByCity(filters.cityCode)" style="width:150px;" clearable>
						<el-option v-for="(item,i) in cityList" :key="i" :label="item.name" :value="item.code"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-select v-model="filters.districtCode" placeholder="请选择区县" style="width:150px;" clearable>
						<el-option v-for="(item,i) in districtList" :key="i" :label="item.name" :value="item.code"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item>
				 	<el-input  placeholder="请输入学校" v-model="filters.schoolName"  style="width:180px;" clearable ></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getSchools">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="tableData" highlight-current-row v-loading="listLoading" style="width: 100%;">
			<el-table-column type="index" label="序号" width="50" align='center'>
				<template slot-scope="scope">   
                    {{pageSize*(nowPage-1)+scope.$index+1}}
                </template>
			</el-table-column>
			<el-table-column prop="schoolName" label="学校" min-width="230" align='center' >
			</el-table-column>
			<el-table-column  label="所属地区" width="150" min-align='center' >
				<template slot-scope="scope">
                    {{scope.row.provinceName}}{{scope.row.cityName == '市辖区'?'':scope.row.cityName}}{{scope.row.districtName== '市辖区'?'':scope.row.districtName}}
                </template>
			</el-table-column>
			<el-table-column prop="phase" label="学段" min-width="150" align='center' >
                <template slot-scope="scope">
                    <span v-for="(item,index) in scope.row.schoolPhaseList" :key="index">{{item.phaseName}}{{index==(scope.row.schoolPhaseList.length-1)?"":"、"}}</span>
                </template>
            </el-table-column>
			<el-table-column prop="useType" label="状态" width="50">
				<template slot-scope="scope">
					{{scope.row.useType=="0"?"正常":"停用"}}
				</template>
			</el-table-column>
			<el-table-column label="操作" width="360" align='center' fixed="right" >
				<template slot-scope="scope">
					<el-button type="primary" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
					<el-button v-if="scope.row.useType==0" type="info" size="small" @click="offSchool(scope.row)">停用</el-button>
					<el-button v-else  size="small" type="success" @click="onSchool(scope.row)">启用</el-button>
					<el-button v-if="checkMenu('/schoolproduct')>=0" type="warning" size="small" @click="handleProduct(scope.row)">产品</el-button>
					<el-button v-if="checkMenu('/campus')>=0" type="primary" size="small" @click="handleManage(scope.row)">管理</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination background layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="text-align: center; ">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog :title="editType" :visible.sync="editFormVisible" :close-on-click-modal="false" :before-close="closeDialog" :append-to-body="false" v-loading="editLoading">
			<el-form :model="schoolForm" label-width="120px" :rules="schoolRules" ref="schoolForm">
				<el-form-item label="学校名称" prop="schoolName">
					<el-input v-model="schoolForm.schoolName" placeholder="请输入学校名称，最长50个汉字" style="float:left;width:90%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="学校简称" prop="shortName">
					<el-input v-model="schoolForm.shortName" placeholder="请输入学校简称，最长20个汉字" style="float:left;width:90%;" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="学校简介" prop="descript">
					<el-input v-model="schoolForm.descript" type="textarea" placeholder="请输入学校简介"
					:autosize="{minRows: 4, maxRows: 4}" :style="{width: '100%'}"></el-input>
				</el-form-item>
				<el-form-item label="所属地区：" required>
					<el-form-item prop="provinceCode" style="float:left;width:25%;">
						<el-select v-model="schoolForm.provinceCode" @change="getCityListByProvince(schoolForm.provinceCode)" placeholder="请选择省份">
							<el-option v-for="(i,j) in provinceList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="cityCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="schoolForm.cityCode" :disabled="schoolForm.provinceCode==''" @change="getDistrictListByCity(schoolForm.cityCode)" placeholder="请选择地市">
							<el-option v-for="(i,j) in cityList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
					<el-form-item prop="districtCode" style="float:left;width:25%;margin-left:5px;">
						<el-select v-model="schoolForm.districtCode" :disabled="schoolForm.cityCode==''" placeholder="请选择区县">
							<el-option v-for="(i,j) in districtList" :label="i.name" :value="i.code" :key="j"></el-option>
						</el-select>
					</el-form-item>
				</el-form-item>
				<el-form-item label="学段" prop="phases">
					<el-checkbox-group v-model="schoolForm.phases">

						<el-checkbox  v-for="item in phaseList" :label="item.phaseId" :key="item.phaseId" name="type">{{item.phaseName}}</el-checkbox>
					</el-checkbox-group>
				</el-form-item>
				<el-form-item label="学校地址" prop="address">
					<el-input v-model="schoolForm.address" placeholder="请输入学校地址，最长50个汉字" style="float:left;width:90%;"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="closeDialog">取消</el-button>
				<el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
			</div>
		</el-dialog>

	</section>
</template>

<script>
	import util from '../../common/js/util'
	import { SysApi } from '@/api/index'

	export default {
		data() {
			var isInteger = (rule, value, callback) => {
				if (!value) {
					return callback(new Error('输入不可以为空'));
				}
				setTimeout(() => {
					if (!Number(value)) {
						callback(new Error('请输入正整数'));
					} else {
						const re = /^[0-9]*[1-9][0-9]*$/;
						const rsCheck = re.test(value);
						if (!rsCheck) {
							callback(new Error('请输入正整数'));
						} else {
							callback();
						}
					}
				}, 1000);
			};
			return {
				filters: {
					schoolName: '',
					provinceCode: '',
					cityCode: '',
					districtCode: ''
				},
				tableData: [],
				phaseList: [],
				provinceList: [],
				cityList: [],
				districtList: [],
				menuList: [],
				total: 0,
				adminId: '',
				listLoading: true,
				loading_search: true,

				//学校信息表单
				schoolForm: {
					schoolId: '',
					schoolName: '',
					shortName: '',
					provinceCode: '',
					cityCode: '',
					districtCode: '',
					address: '',
					homepageUrl: '',
					logo: '',
					descript: '',
					classesNum: '',
					provinceName: '',
					cityName: '',
					districtName: '',
					useType: 0,
					schoolPhaseList: [],
					phases: []
				},

				editType: '',

				editFormVisible: false,//编辑界面是否显示
				editLoading: false,

				schoolRules: { //学校信息表单验证
					schoolName:[
						{ required: true, message: '请填写学校名称', trigger: 'blur'},
						{ min: 1, max: 50, message: '学校名称长度为 1 到 50 个字符', trigger: ['blur','change'] }
					],
					shortName:[
						{ min: 1, max: 20, message: '学校简称长度为 1 到 20 个字符', trigger: ['blur','change'] }
					],
					descript:[
						{ min: 1, max: 200, message: '学校简介长度为 1 到 200 个字符', trigger: ['blur','change'] }
					],
					address:[
						{ min: 1, max: 50, message: '学校地址长度为 1 到 50 个字符', trigger: ['blur','change'] }
					],
					districtCode:[
						{ required: true, message: '请选择所属地区', trigger: ['blur','change'] } 
					],
					phases:[
						{ required: true, message: '请选择学段', trigger: 'blur' } 
					],
            },
            pageSize:10,
            nowPage:1,

			}
		},
		created(){
	
			this.getMenuList();
			this.getPhaseList();
			this.getProvinceList();
			this.getSchools();
			
		},
		mounted() {
			this.getSchools();
		},
		methods: {
			handleCurrentChange(val) {
				this.nowPage = val;
				this.getSchools();
			},
			getMenuList(){
				this.menuList = sessionStorage.getItem('menuList');
			},
			//获取省列表
			getProvinceList(){
				let params = {
					parentcode: '0'

				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.provinceList = res;
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
			},
			//市相对省联动
			getCityListByProvince(parentcode){
				
				let params = {
					parentcode: parentcode
				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.cityList = res;
					this.filters.cityCode =  '';
					this.filters.districtCode =  '';
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
			
			},
			//区相对市联动
			getDistrictListByCity(parentcode){
				
				let params = {
					parentcode: parentcode
				};
				this.loading_search = true;
				SysApi.getDistrictList(params,res =>{
					this.districtList = res;
					this.filters.districtCode =  '';
					this.loading_search = false;
				}, (errorType, error) => {
					this.loading_search = false;
				})
				
			},
			//获取学段列表
			getPhaseList(){
				SysApi.getPhaseList({}, res => {
					this.phaseList = res;
				}, (errorType, error) => {
				})
			},
			//获取学校列表
			getSchools() {
				let params = {
					pageNum: this.nowPage,
					pageSize: this.pageSize,
					provinceCode: this.filters.provinceCode,
					cityCode: this.filters.cityCode,
					districtCode: this.filters.districtCode,
					schoolName: this.filters.schoolName

				};
				this.listLoading = true;

				SysApi.getAllSchoolListPage(params,res =>{
					this.total = res.total;
					this.tableData = res.list;
					this.listLoading = false;
				}, (errorType, error) => {
					this.listLoading = false;
				})

			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
	
					let params = {
						 schoolId: row.schoolId
						 };

					SysApi.deleteSchool(params,res =>{
						this.listLoading = false;
						if (res!=null)
						{
							this.$message({
								message: '删除成功',
								type: 'success'
							});
						}
						this.getSchools();
					}, (errorType, error) => {
						this.listLoading = false;
					}).catch((error) => {
						this.listLoading = false;
					})
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
				this.editType = "编辑";
				this.editLoading = true;
				this.schoolForm = Object.assign({}, row);
				this.schoolForm.provinceCode=row.provinceCode
				this.getCityListByProvince(row.provinceCode);
				this.schoolForm.cityCode=row.cityCode
				this.getDistrictListByCity(row.cityCode);
				this.schoolForm.districtCode=row.districtCode
				this.editFormVisible = true;
				this.editLoading = false;
				
			},
			//显示新增界面
			handleAdd: function () {
				this.editType = "新增";
				this.editLoading = true;

				this.schoolForm.schoolId =  '';
				this.schoolForm.schoolName =  '';
				this.schoolForm.shortName =  '';
				this.schoolForm.provinceCode =  '';
				this.schoolForm.cityCode =  '';
				this.schoolForm.districtCode =  '';
				this.schoolForm.address =  '';
				this.schoolForm.homepageUrl =  '';
				this.schoolForm.logo =  '';
				this.schoolForm.descript =  '';
				this.schoolForm.classesNum =  '';
				this.schoolForm.provinceName =  '';
				this.schoolForm.cityName =  '';
				this.schoolForm.districtName =  '';
				this.schoolForm.useType = 0;

				this.editFormVisible = true;
				this.editLoading = false;
				this.$refs['schoolForm'].resetFields();
		
			},
			//编辑
			editSubmit: function () {
				this.$refs.schoolForm.validate((valid) => {
					if (valid) {
							
							let params = Object.assign({}, this.schoolForm);
							
							SysApi.saveSchool(params,res =>{
								this.listLoading = false;
								this.$message({
									message: '提交成功',
									type: 'success'
								});
								this.$refs['schoolForm'].resetFields();
								this.editFormVisible = false;
								this.getSchools();
							}, (errorType, error) => {
								this.$message({type: 'error', message: '提交失败!'})
								// console.log("error=");
								// console.log(error);
	
							})
							
					}
				});
			},
			closeDialog: function () {
				this.$refs['schoolForm'].resetFields();
				this.editFormVisible = false;
			},
			onSchool(row){
				this.$confirm('是否启用学校?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.onSchool({
						schoolId: row.schoolId
					}, res => {
						this.$message({type: 'success', message: '启用成功!'})
						this.getSchools();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '启用失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			offSchool(row) {
				this.$confirm('是否停用学校?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					SysApi.offSchool({
						schoolId: row.schoolId
					}, res => {
						this.$message({type: 'success', message: '停用成功!'})
						this.getSchools();
					}, (errorType, error) => {
						this.$message({type: 'error', message: '停用失败!'})
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
			},
			handleProduct(row){
				
				this.$router.push({
					name: '学校产品',
					params: {
						schoolName: row.schoolName,
						schoolId: row.schoolId
					}
				});
			},
			handleManage(row){
				var path = this.getCampusMenu();
				sessionStorage.setItem('schoolId',JSON.stringify(row.schoolId))
				sessionStorage.setItem('schoolName',JSON.stringify(row.schoolName))
				sessionStorage.setItem('provinceCode',JSON.stringify(row.provinceCode))
				sessionStorage.setItem('cityCode',JSON.stringify(row.cityCode))
				sessionStorage.setItem('districtCode',JSON.stringify(row.districtCode))
				this.$router.push({
					path: path,
					params:{
						schoolId: row.schoolId,
						schoolName: row.schoolName
					}
				});
			},
			//判断菜单是否可见
			checkMenu(item){

				if (this.menuList==null || this.menuList.length==0)
				{
					return -1;
				}
				var index = this.menuList.indexOf(item);
				return index
			},
			getCampusMenu(){

				var index = -1;
				index = this.menuList.indexOf('/schoolinfo');
				if (index>=0)
					return '/schoolinfo'

				index = this.menuList.indexOf('/schoolteacher');
				if (index>=0)
					return '/schoolteacher'

				index = this.menuList.indexOf('/classes');
				if (index>=0)
					return '/classes'

				index = this.menuList.indexOf('/schoolstudent');
				if (index>=0)
					return '/schoolstudent'

				index = this.menuList.indexOf('/schoolrole');
				if (index>=0)
					return '/schoolrole'
				
			}

		},
		
	}

</script>

<style>
.el-table >.el-table__fixed {
    height: 100% !important; 
  }
.el-table >.el-table__fixed-right {
    height: 100% !important; 
  }
.el-table--scrollable-x .el-table__body-wrapper {
    z-index: 1;
  }
</style>